/*
 * BackupFileDAO.java
 *
 * Created on April 11, 2007, 10:56 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * @author Dallin Regehr
 */
public class BackupFileDAO {
    private static BackupFileDAO instance = null;
    
    /** Creates a new instance of RSSFeedDAO */
    private BackupFileDAO() {
    }
    
    public static synchronized BackupFileDAO getInstance() {
        if (instance == null) {
            instance = new BackupFileDAO();
        }
        return instance;
    }
    
    
    /////////////////////////////////
    ///   CREATE
    
    public BackupFileBO create() throws Exception {
        String id = GUID.generate();
        BackupFileBO BackupFile = new BackupFileBO(id);
        Cache c = Cache.getInstance();
        c.put(BackupFile.getId(), BackupFile);
        return BackupFile;
    }
    
    public BackupFileBO create(String id){
        BackupFileBO BackupFile = new BackupFileBO(id);
        Cache c = Cache.getInstance();
        c.put(BackupFile.getId(),BackupFile);
        return BackupFile;
    }
    
    
    /////////////////////////////////////
    ///   READ
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized BackupFileBO read(String id) throws DataException {
        BackupFileBO BackupFile;
        Connection conn;
        // check to see if id in the cache
        // if so, return it immediately
        if(Cache.getInstance().containsKey(id)){
            return (BackupFileBO) Cache.getInstance().get(id);
        }
        
        
        try {
            
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            
            // call read with a connection (the other read method in this class)
            BackupFile = BackupFileDAO.getInstance().read(id,conn);
            
            // release the connection
            ConnectionPool.getInstance().release(conn);
            // rollback
            conn.rollback();
        }catch (ConnectionPoolException ex) {
            throw new DataException("Unable to communicate with the Database", ex);
            
        }catch (SQLException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        return BackupFile;
    }
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    public BackupFileBO read(String id,Connection conn) throws DataException {
        BackupFileBO BackupFile=null;
        // check the cache to see if the customer is in the cache
        // if so, return it immediately
        if(Cache.getInstance().containsKey(id)){
            return (BackupFileBO) Cache.getInstance().get(id);
        }
        
        try{
            PreparedStatement pstmt =conn.prepareStatement("Select * from \"BackupFileship\" WHERE id=?");
            pstmt.setString(1,id);
            
            ResultSet rs = null;
            rs = pstmt.executeQuery();
            // get a rs from an sql SELECT statement
            // if( rs.next()){convert the rs to the BackupFile}
            if(rs.next()){
                BackupFile = BackupFileDAO.getInstance().create(id);
                BackupFile.setCustomerID(rs.getString("CustomerID"));
                BackupFile.setFileName(rs.getString("FileName"));
                BackupFile.setDateAdded(rs.getDate("DateAdded"));
                //read in the file bytes not included here
                BackupFile.setSize(rs.getDouble("Size"));
                BackupFile.setExtension(rs.getString("Extension"));
                
                //save to the cache
                BackupFile.setAlreadyInDB(true);
                Cache.getInstance().put(BackupFile.getId(),BackupFile);
   
            }
        }catch(SQLException e){
            //rollback
            throw new DataException("Could not retrieve record for id=" + id,e);
        }
        //release the connection back to the pool.
        return BackupFile;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     */
    public synchronized void save(BackupFileBO BackupFile) throws DataException {
        
        try {
            // retrieve a database connection from the pool
            Connection conn=ConnectionPool.getInstance().get();
            // call save with a connection (the other save method in this class)
            save(BackupFile, conn);
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }catch (SQLException e) {
            // rollback
            throw new DataException("Could not save record for id=" + BackupFile.getId(), e);
        }catch (ConnectionPoolException e){
            throw new DataException("Could not retrieve Connection", e);
        }
        
        // release the connection back to the pool
        
    }
    
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the CustomerDAO calling
     *  BackupFileshipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     */
    synchronized void save(BackupFileBO BackupFile, Connection conn) throws SQLException, DataException {
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (BackupFile.isDirty()) {
            if (BackupFile.isAlreadyInDB()) {
                update(BackupFile, conn);
            }else{
                insert(BackupFile, conn);
            }
            // set the dirty flag to false now that we've saved it
            BackupFile.setDirty(false);
        }
        
        // call save(bo, conn) on any subobjects (like CustomerDAO to BackupFileshipDAO)
        /*This next line was removed because we don't have all of the code to remediate the circulare saves.
         CustomerDAO.getInstance().save(BackupFile.getCustomer(),conn);
         **/
        // touch the cache for the object
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(BackupFileBO BackupFile,Connection conn) throws SQLException, DataException {
        // do the update statement
        PreparedStatement pstmt =conn.prepareStatement("UPDATE \"BackupFileship\" SET \"CustomerID\" = ?," +
                " \"FileName\" = ?," +
                " \"DateAdded\" = ?," +
                " \"File\" = ?" +
                " \"Size\" = ?" +
                " \"Extension\" = ?" +
                " WHERE \"ID\" = ?");
        pstmt.setString(1,BackupFile.getCustomerID());
        pstmt.setString(2,BackupFile.getFileName());
        pstmt.setDate(3, (java.sql.Date) BackupFile.getDateAdded());
        pstmt.setBinaryStream(4,BackupFile.getFileInStream());
        pstmt.setDouble(5,BackupFile.getSize());
        pstmt.setString(6,BackupFile.getExtension());
        pstmt.setString(7,BackupFile.getId());
        pstmt.executeUpdate();
        
        System.out.println("BackupFileUpdateSuccessful");
    }
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(BackupFileBO BackupFile,Connection conn) throws SQLException, DataException {
        // do the insert SQL statement
        try{
        PreparedStatement pstmt =conn.prepareStatement("INSERT INTO \"BackupFiles\" VALUES (?,?,?,?,?,?,?)");
        System.out.println("1");
        pstmt.setString(1,BackupFile.getId());
        System.out.println("2");
        pstmt.setString(2,BackupFile.getCustomerID());
        System.out.println("3");
        pstmt.setString(3,BackupFile.getFileName());
        System.out.println("4");
        pstmt.setDate(4, null);//(java.sql.Date) BackupFile.getDateAdded());
        System.out.println("5");
        pstmt.setBinaryStream(5,BackupFile.getFileInStream(),(int)BackupFile.getSize());
        System.out.println("6");
        pstmt.setDouble(6,BackupFile.getSize());
        System.out.println("7");
        pstmt.setString(7,BackupFile.getExtension());
        System.out.println("8");
        pstmt.execute();
        System.out.println("BackupFileInsertSucessful");
        }catch(Exception e){
            throw new DataException("Could not insert backup file",e);
        }
        // tell the object that it's now in the db (so we call update next time not insert)
        BackupFile.setAlreadyInDB(true);
    }
    
    ////////////////////////////////////
    ///   DELETE
    
    // We have decided not to support delete because we would like the BackupFiles to stay in the database for data archiving.
    
    //////////////////////////////
    ///  SEARCH methods
    
    public List<BackupFileBO> getAllCustBackupFiles(CustomerBO cust) throws DataException {
        List<BackupFileBO> fileList = null;
        // get the connection
        Connection conn=null;
        try {
            conn=ConnectionPool.getInstance().get();
            
            fileList = new ArrayList<BackupFileBO>();
            
            PreparedStatement pstmt =conn.prepareStatement("Select * from \"BackupFiles\" Where \"CustomerID\" =?");
            pstmt.setString(1, cust.getId());
            ResultSet rs = pstmt.executeQuery();
            // get a rs from an sql SELECT statement
            if(rs.next()){
                do{
                    BackupFileBO file = new BackupFileBO(rs.getString("ID"));
                    file.setCustomerID(rs.getString("CustomerID"));
                    file.setFileName(rs.getString("FileName"));
                    file.setDateAdded(rs.getDate("DateAdded"));
                    //file.setFile(null);// we want to only load the stream
                    file.setSize(rs.getFloat("Size"));
                    file.setExtension(rs.getString("Extension"));
                    fileList.add(file);
                }while(rs.next());
                
            }else{
                //no files were found
                fileList = null;
            }
        } catch (ConnectionPoolException e){
            throw new DataException("Could not retrieve Connection", e);
        } catch (SQLException ex){
            throw new DataException("Error reading from database",ex);
        }
        return fileList;
    }
  
}